<template>
    <!-- 任务 -->
    <div class="task">
        <!-- 审批人设置 -->
        <el-row>
            <h4><b>审批人设置</b></h4>
            <el-radio-group v-model="dataType" @change="changeDataType">
                <el-radio label="USERS">指定用户</el-radio>
                <el-radio label="ROLES">角色</el-radio>
                <el-radio label="DEPTS">部门</el-radio>
                <el-radio label="INITIATOR">发起人</el-radio>
            </el-radio-group>
        </el-row>
        <!-- 添加用户 -->
        <el-row>
            <div v-if="dataType === 'USERS'">
                <el-tag
                    v-for="userText in user.selectedUser.text"
                    :key="userText"
                    effect="plain"
                    size="mini"
                >
                    {{ userText }}
                </el-tag>
                <div class="element-drawer__button">
                    <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-plus"
                        @click="onSelectUsers()"
                        >添加用户</el-button
                    >
                </div>
            </div>
        </el-row>
        <!-- 添加角色 -->
        <div v-if="dataType === 'ROLES'">
            <el-select
                v-model="role.roleIds"
                multiple
                size="mini"
                placeholder="请选择角色"
                @change="changeSelectRoles"
            >
                <el-option
                    v-for="item in role.roleOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="`ROLE${item.id}`"
                    :disabled="item.status === '1'"
                />
            </el-select>
        </div>
        <!-- 添加部门 -->
        <div v-if="dataType === 'DEPTS'">
            <tree-select
                :width="320"
                :height="400"
                size="mini"
                :data="dept.deptTreeData"
                :defaultProps="dept.deptProps"
                multiple
                clearable
                checkStrictly
                nodeKey="id"
                :checkedKeys="dept.deptIds"
                @change="checkedDeptChange"
            />
        </div>
        <!-- 多审批方式 -->
        <el-row>
            <div v-show="showMultiFlog">
                <el-divider />
                <h4><b>多实例审批方式</b></h4>
                <el-row>
                    <el-radio-group
                        v-model="multiLoopType"
                        @change="changeMultiLoopType()"
                    >
                        <el-row><el-radio label="Null">无</el-radio></el-row>
                        <el-row
                            ><el-radio label="SequentialMultiInstance"
                                >会签（需所有审批人同意）</el-radio
                            ></el-row
                        >
                        <el-row
                            ><el-radio label="ParallelMultiInstance"
                                >或签（一名审批人同意即可）</el-radio
                            ></el-row
                        >
                    </el-radio-group>
                </el-row>
                <el-row v-if="multiLoopType !== 'Null'">
                    <el-tooltip
                        content="开启后，实例需按顺序轮流审批"
                        placement="top-start"
                        @click.stop.prevent
                    >
                        <i class="header-icon el-icon-info"></i>
                    </el-tooltip>
                    <span class="custom-label">顺序审批：</span>
                    <el-switch
                        v-model="isSequential"
                        @change="changeMultiLoopType()"
                    />
                </el-row>
            </div>
        </el-row>
        <!-- 添加用户的弹框 -->
        <!-- 弹框 -->
        <el-dialog
            title="选择用户"
            :visible.sync="user.checkedUserDialog"
            width="80%"
            v-dialogDrag
            append-to-body
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <div class="checked-user">
                <checked-user ref="checkedUser" />
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="handelCloseDialog"
                    >取 消</el-button
                >
                <el-button
                    size="small"
                    type="primary"
                    @click="handelCofimeDialog"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import CheckedUser from '@/components/checkedUser/index'
import TreeSelect from '../../treeSelect/index.vue'
import { roleListAll } from '@/http/apis/system/role'
import { deptTree } from '@/http/apis/system/dept'
const userTaskForm = {
    dataType: '',
    assignee: '',
    candidateUsers: '',
    candidateGroups: '',
    text: ''
}
export default {
    components: {
        CheckedUser,
        TreeSelect
    },
    watch: {
        id: {
            immediate: true,
            handler() {
                this.bpmnElement = window.bpmnInstances.bpmnElement
                this.$nextTick(() => this.resetTaskForm())
            }
        }
    },
    beforeDestroy() {
        this.bpmnElement = null
    },
    data() {
        return {
            // 审批人类型
            dataType: '',
            // 用户相关
            user: {
                // 选中的用户
                selectedUser: {
                    ids: [],
                    text: []
                },
                // 选中的用户列表
                selectedUserDate: [],
                // 选择用户的弹框
                checkedUserDialog: false
            },
            // 角色相关
            role: {
                // 角色列表
                roleOptions: [],
                // 选中的角色列表
                roleIds: []
            },
            // 部门相关
            dept: {
                // 部门树列表
                deptTreeData: [],
                // 默认选中的数据
                deptIds: [],
                // 过滤条件是否显示
                filterShow: true,
                deptProps: {
                    children: 'children',
                    label: 'label'
                }
            },
            // 多实例审批方式是否显示
            showMultiFlog: false,
            // 审批方式类型
            multiLoopType: 'Null',
            isSequential: false
        }
    },
    methods: {
        /**
         * 初始化表单
         */
        resetTaskForm() {
            const bpmnElementObj = this.bpmnElement?.businessObject
            if (!bpmnElementObj) {
                return
            }
            //this.clearOptionsData()
            this.dataType = bpmnElementObj['dataType']
            if (this.dataType === 'USERS') {
                let userIdData =
                    bpmnElementObj['candidateUsers'] ||
                    bpmnElementObj['assignee']
                let userText = bpmnElementObj['text'] || []
                if (
                    userIdData &&
                    userIdData.toString().length > 0 &&
                    userText &&
                    userText.length > 0
                ) {
                    this.user.selectedUser.ids = userIdData
                        ?.toString()
                        .split(',')
                    this.user.selectedUser.text = userText?.split(',')
                }
                if (this.user.selectedUser.ids.length > 1) {
                    this.showMultiFlog = true
                }
            } else if (this.dataType === 'ROLES') {
                this.featchRoleList()
                let roleIdData = bpmnElementObj['candidateGroups'] || []
                if (roleIdData && roleIdData.length > 0) {
                    this.role.roleIds = roleIdData.split(',')
                }
                this.showMultiFlog = true
            } else if (this.dataType === 'DEPTS') {
                this.featchDeptList()
                let deptIdData = bpmnElementObj['candidateGroups'] || []
                if (deptIdData && deptIdData.length > 0) {
                    this.dept.deptIds = deptIdData.split(',')
                }
                this.showMultiFlog = true
            }
            this.getElementLoop(bpmnElementObj)
        },
        getElementLoop(businessObject) {
            if (!businessObject.loopCharacteristics) {
                this.multiLoopType = 'Null'
                return
            }
            this.isSequential = businessObject.loopCharacteristics.isSequential
            if (businessObject.loopCharacteristics.completionCondition) {
                if (
                    businessObject.loopCharacteristics.completionCondition
                        .body === '${nrOfCompletedInstances >= nrOfInstances}'
                ) {
                    this.multiLoopType = 'SequentialMultiInstance'
                } else {
                    this.multiLoopType = 'ParallelMultiInstance'
                }
            }
        },
        /**
         * 清空选项数据
         */
        clearOptionsData() {
            this.user.selectedUser.ids = []
            this.user.selectedUser.text = []
            this.role.roleIds = []
            this.dept.deptIds = []
        },
        /**
         * 切换审批人类型
         */
        changeDataType(val) {
            if (
                val === 'ROLES' ||
                val === 'DEPTS' ||
                (val === 'USERS' && this.user.selectedUser.ids.length > 1)
            ) {
                this.showMultiFlog = true
            } else {
                this.showMultiFlog = false
            }
            this.multiLoopType = 'Null'
            this.changeMultiLoopType()
            // 清空 userTaskForm 所有属性值
            Object.keys(userTaskForm).forEach(key => (userTaskForm[key] = null))
            userTaskForm.dataType = val
            if (val === 'USERS') {
                if (
                    this.user.selectedUser &&
                    this.user.selectedUser.ids &&
                    this.user.selectedUser.ids.length > 0
                ) {
                    if (this.user.selectedUser.ids.length === 1) {
                        userTaskForm.assignee = this.user.selectedUser.ids[0]
                    } else {
                        userTaskForm.candidateUsers = this.user.selectedUser.ids.join()
                    }
                    userTaskForm.text =
                        this.user.selectedUser.text?.join() || null
                }
            } else if (val === 'ROLES') {
                this.featchRoleList()
                if (this.role.roleIds && this.role.roleIds.length > 0) {
                    userTaskForm.candidateGroups =
                        this.role.roleIds.join() || null
                    let textArr = this.role.roleOptions.filter(
                        k => this.role.roleIds.indexOf(`ROLE${k.id}`) >= 0
                    )
                    userTaskForm.text = textArr?.map(k => k.name).join() || null
                }
            } else if (val === 'DEPTS') {
                this.featchDeptList()
                if (this.dept.deptIds && this.dept.deptIds.length > 0) {
                    userTaskForm.candidateGroups =
                        this.dept.deptIds.join() || null
                    let textArr = []
                    let treeStarkData = JSON.parse(
                        JSON.stringify(this.dept.deptTreeData)
                    )
                    this.dept.deptIds.forEach(id => {
                        let stark = []
                        stark = stark.concat(treeStarkData)
                        while (stark.length) {
                            let temp = stark.shift()
                            if (temp.children) {
                                stark = temp.children.concat(stark)
                            }
                            if (id === temp.id) {
                                textArr.push(temp)
                            }
                        }
                    })
                    userTaskForm.text =
                        textArr?.map(k => k.label).join() || null
                }
            } else if (val === 'INITIATOR') {
                userTaskForm.assignee = '${initiator}'
                userTaskForm.text = '流程发起人'
            }
            this.updateElementTask()
        },

        // 用户相关
        /**
         * 添加用户被点击
         */
        onSelectUsers() {
            // 将选中的用户列表清空
            this.user.selectedUserDate = []
            this.user.checkedUserDialog = true
            // 将用户表格上的选中数据清空
            this.$refs['checkedUser']?.clearCheckedUser()
        },
        /**
         * 确定添加用户
         */
        handelCofimeDialog() {
            this.user.selectedUserDate = this.$refs[
                'checkedUser'
            ].getCheckedUser()
            if (
                !this.user.selectedUserDate ||
                this.user.selectedUserDate.length <= 0
            ) {
                this.$modal.msgError('请选择用户')
                return
            }
            userTaskForm.dataType = 'USERS'
            this.user.selectedUser.text =
                this.user.selectedUserDate.map(k => k.userName) || []
            if (this.user.selectedUserDate.length === 1) {
                let data = this.user.selectedUserDate[0]
                userTaskForm.assignee = data.userId
                userTaskForm.text = data.userName
                userTaskForm.candidateUsers = null
                this.showMultiFlog = false
                this.multiLoopType = 'Null'
                this.changeMultiLoopType()
            } else {
                userTaskForm.candidateUsers =
                    this.user.selectedUserDate.map(k => k.userId).join() || null
                userTaskForm.text =
                    this.user.selectedUserDate.map(k => k.userName).join() ||
                    null
                userTaskForm.assignee = null
                this.showMultiFlog = true
            }
            // 更新节点数据
            this.updateElementTask()
            // 关闭用户选择弹框
            this.handelCloseDialog()
        },
        /**
         * 添加用户弹框关闭
         */
        handelCloseDialog() {
            this.user.checkedUserDialog = false
        },

        // 角色相关
        /**
         * 查询角色
         */
        async featchRoleList() {
            let res = await roleListAll()
            this.role.roleOptions = res.data
        },
        /**
         * 选择的角色改变
         */
        changeSelectRoles(val) {
            let groups = null
            let text = null
            if (val && val.length > 0) {
                userTaskForm.dataType = 'ROLES'
                groups = val.join() || null
                let textArr = this.role.roleOptions.filter(
                    k => val.indexOf(`ROLE${k.id}`) >= 0
                )
                text = textArr?.map(k => k.name).join() || null
            } else {
                userTaskForm.dataType = null
                this.multiLoopType = 'Null'
            }
            userTaskForm.candidateGroups = groups
            userTaskForm.text = text
            this.updateElementTask()
            this.changeMultiLoopType()
        },

        // 部门相关
        /**
         * 查询部门数据
         */
        async featchDeptList() {
            let res = await deptTree()
            this.dept.deptTreeData = res.data
        },
        /**
         * 部门选择
         */
        checkedDeptChange(checkedIds) {
            let groups = null
            let text = null
            this.dept.deptIds = checkedIds
            if (checkedIds && checkedIds.length > 0) {
                userTaskForm.dataType = 'DEPTS'
                groups = checkedIds.join() || null
                let textArr = []
                let treeStarkData = JSON.parse(
                    JSON.stringify(this.dept.deptTreeData)
                )
                checkedIds.forEach(id => {
                    let stark = []
                    stark = stark.concat(treeStarkData)
                    while (stark.length) {
                        let temp = stark.shift()
                        if (temp.children) {
                            stark = temp.children.concat(stark)
                        }
                        if (id === temp.id) {
                            textArr.push(temp)
                        }
                    }
                })
                text = textArr?.map(k => k.label).join() || null
            } else {
                userTaskForm.dataType = null
                this.multiLoopType = 'Null'
            }
            userTaskForm.candidateGroups = groups
            userTaskForm.text = text
            this.updateElementTask()
            this.changeMultiLoopType()
        },
        /**
         * 更新节点数据
         */
        updateElementTask() {
            const taskAttr = Object.create(null)
            for (let key in userTaskForm) {
                taskAttr[key] = userTaskForm[key]
            }
            console.log('taskAttr', taskAttr)
            window.bpmnInstances.modeling.updateProperties(
                this.bpmnElement,
                taskAttr
            )
        },
        /**
         *修改审批项显示
         */
        changeMultiLoopType() {
            // 取消多实例配置
            if (this.multiLoopType === 'Null') {
                window.bpmnInstances.modeling.updateProperties(
                    this.bpmnElement,
                    { loopCharacteristics: null, assignee: null }
                )
                return
            }
            this.multiLoopInstance = window.bpmnInstances.moddle.create(
                'bpmn:MultiInstanceLoopCharacteristics',
                { isSequential: this.isSequential }
            )
            // 更新多实例配置
            window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
                loopCharacteristics: this.multiLoopInstance,
                assignee: '${assignee}'
            })
            // 完成条件
            let completionCondition = null
            // 会签
            if (this.multiLoopType === 'SequentialMultiInstance') {
                completionCondition = window.bpmnInstances.moddle.create(
                    'bpmn:FormalExpression',
                    { body: '${nrOfCompletedInstances >= nrOfInstances}' }
                )
            }
            console.log(completionCondition)
            // 或签
            if (this.multiLoopType === 'ParallelMultiInstance') {
                completionCondition = window.bpmnInstances.moddle.create(
                    'bpmn:FormalExpression',
                    { body: '${nrOfCompletedInstances > 0}' }
                )
            }
            console.log(' window.bpmnInstances.modeling', window.bpmnInstances)
            // 更新模块属性信息
            window.bpmnInstances.modeling.updateModdleProperties(
                this.bpmnElement,
                this.multiLoopInstance,
                {
                    collection: '${multiInstanceHandler.getUserIds(execution)}',
                    elementVariable: 'assignee',
                    completionCondition
                }
            )
        }
    }
}
</script>
<style lang="scss" scoped>
.task {
    .el-row .el-radio-group {
        margin-bottom: 15px;
        .el-radio {
            line-height: 28px;
        }
    }
}
.checked-user {
    @include box_flex(
        $width: 100%,
        $height: 60vh,
        $direction: row,
        $justify: flex-start,
        $align: flex-start
    );
}
</style>
